import React, { useState } from 'react';
import { connect } from 'dva';
import { Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import ImgCrop from 'antd-img-crop';
import styles from './style.less';

const CutBox = (props) => {
  const { cardIns, dispatch } = props;
  const [fileList, setFileList] = useState();

  const feedImage = async (file: { url: string, originFileObj: Blob }) => {
    let src = file.url;
    if (!src) {
      src = await new Promise(resolve => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    image.onload = () => {
      cardIns?.feed(image);
    };

    // 设置背景
    dispatch({
      type: 'cardData/change-center-image',
      payload: src,
    });
  }

  const onChange = (value: { fileList: any }) => {
    const { fileList } = value;

    while(fileList.length > 3) {
      fileList.shift();
    }

    setFileList(fileList);

    if (fileList.length > 0) {
      feedImage(fileList[fileList.length - 1]);
    }
  };

  const onPreview = (file: { url: string, originFileObj: Blob }) => feedImage(file);

  return (
    <ImgCrop rotate>
      <Upload
        className={styles.cutbox}
        listType="picture-card"
        fileList={fileList}
        onChange={onChange}
        onPreview={onPreview}
      >
        <UploadOutlined />
      </Upload>
    </ImgCrop>
  );
};

const mapStateToProps = ({ cardData }) => {
  const { cardIns } = cardData;
  return {
    cardIns,
  }
};

export default connect(mapStateToProps)(CutBox);
